import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import sqlite3
from config import mail_receivers,sender,mail_host,mail_pwd,mail_user

def sendHtmlMail():
    msgRoot = MIMEMultipart('related')
    msgRoot['From'] = Header(sender, 'utf-8')
    msgRoot['To'] = Header(";".join(mail_receivers), 'utf-8')
    subject = '123'
    msgRoot['Subject'] = Header(subject, 'utf-8')
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
    mail_msg = """
    <h3>开源代码网站关键词监控(gitee,github)</h3>
    <br>
    <br>
    <table border="1">
  <tr>
    <th>仓库地址</th>
    <th>查询关键词</th>
    <th>创建时间</th>
  </tr>
    """
    # 查询数据库
    conn = sqlite3.connect("project_info.db")
    cursor = conn.cursor()
    rows = cursor.execute("select * from project where notify_times < 3 ")
    msg_html = ""
    for row in rows:
        msg_html += f"<tr><td><a href='{row[0]}'>{row[0]}</a></td><td>{row[1]}</td><td>{row[2]}</td></tr>"
    if msg_html == "":
        return
    mail_msg += msg_html + f'''</table>'''
    mail_msg= '你好'
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    try:
        smtpObj = smtplib.SMTP(mail_host, 25)
        smtpObj.login(mail_user,mail_pwd)
        smtpObj.sendmail(sender, mail_receivers, msgRoot.as_string())
        print("邮件发送完成")
        # 更新数据库
        cursor.execute("update project set notify_times = notify_times+1 where notify_times < 3")
        conn.commit()
        conn.close()
    except Exception as e:
        print("Error: 无法发送邮件", e)

if __name__ == "__main__":
    sendHtmlMail()